// eslint-disable-next-line import/no-unresolved
import React, {Component} from 'react';
import echarts from 'echarts'
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import {dateFormat, convertDateFromString} from '@/utils/time';
import {addResizeHook, removeHook} from '@/utils/resize';
import {connect} from "dva";


class CurrentStatusInfo extends Component {


  state = {
    currentInfo: [],
    cache: {
      latestId: null,
      temp: null,
      location: null,
      tempQueue: [],
      locationQueue: []
    },
    chart: null,
    option: {
      title: {
        text: '当前终点'
      },
      legend: {
        data: ['温度', '位置']
      },
      grid: {
        left: '6%',
        right: '6%',
      },
      tooltip: {
        trigger: 'axis',
        formatter(params) {
          const p = params[0];
          const date = new Date(p.name);
          let display = dateFormat(date);
          if (params[0].value[1] && params[1].value[1]) {
            display = `${display}<br>${params[0].seriesName} ${params[0].value[1].toFixed(2)}℃`;
            display = `${display}<br>${params[1].seriesName} ${params[1].value[1].toFixed(2)}m`;
          }

          return display;
        },
        axisPointer: {
          animation: false
        }
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: false
        }
      },
      yAxis: [{
        type: 'value',
        min: 0,
        max: 600,
        name: '温度/℃',
        // interval: 100,
        splitLine: {
          show: false
        }
      }, {
        type: 'value',
        scale: true,
        name: '位置/m',
        min: 65,
        max: 90,
        interval: 10,
      }],
      series: [
        {
          name: '温度',
          type: 'line',
          yAxisIndex: 0,
          showSymbol: false,
          hoverAnimation: false,
          data: null,
          markLine: {
            symbol: "none",
            smooth: false,
            silent: true,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dotted',
                  color: '#c60c30',
                  width: 2
                },
                label: {
                  show: false,
                  position: 'left'
                }
              }
            },
            // lineStyle: {
            //   normal: {
            //     yAxisIndex: 1,
            //     type: '"dotted',
            //     width: 2
            //   },
            //   label: {
            //     show: false,
            //     position:'left'
            //   }
            // },
            data: [
              {
                yAxis: 320,
                name: "温度上限",
                // itemStyle:{
                //   color:'#c60c30'
                // }
              },

              {
                yAxis: 400,
                name: "温度下限",
                // itemStyle:{
                //   color:'#c60c30'
                // }
              }
            ]

          }
        },
        {
          name: '位置',
          type: 'line',
          yAxisIndex: 1,
          showSymbol: false,
          hoverAnimation: false,
          data: null,
          markArea: { //标记区域
            itemStyle: { //全局的
              normal: {color: '#ff3333'}
            },
            data: [
              [{
                yAxis: 0,//y轴坐标控制
                itemStyle: {
                  color: '#c60c30'
                }
              }, {
                yAxis: 0
              }]
            ]
          },
          markLine: {
            symbol: "none",//去掉箭头
            smooth: false,
            silent: true,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dotted',
                  color: '#5793f3',
                  width: 2
                },
                label: {
                  show: false,
                  position: 'left'
                }
              }
            },
            data: [
              {
                yAxis: 76.44,
                name: "位置上限",
              },

              {
                yAxis: 74.62,
                name: "位置下限",
              }
            ]

          }
        }]
    }
  };


  getLatestId = () => this.state.cache.latestId;


  componentDidMount() {
    const {chartId} = this.props;
    // 基于准备好的dom，初始化echarts实例
    this.state.chart = echarts.init(document.getElementById(chartId));
    // 绘制图表

    this.state.chart.setOption(this.state.option);
    addResizeHook(this, this.state.chart.resize)
  }


  shouldComponentUpdate() {
    return false
  }

  componentWillUnmount() {
    removeHook(this);
  }

  //监听父组件数据更改,return null不做更改
  static getDerivedStateFromProps(nextProps, prevState) {
    const {currentInfo, ruleResult} = nextProps;
    const {option, cache} = prevState
    const result = {}
    // 当传入的type发生变化的时候，更新state
    if (currentInfo && currentInfo !== prevState.currentInfo) {
      currentInfo.forEach(item => {
        if (cache.latestId !== item.id) {

          cache.latestId = item.id;

          const datetime = convertDateFromString(item.time);

          if (cache.tempQueue.length > 360) {
            cache.tempQueue.shift();
            cache.locationQueue.shift();
          }

          cache.tempQueue.push({
            name: datetime, value: [datetime
              , item.temp]
          });
          cache.locationQueue.push({
            name: datetime, value: [datetime
              , item.location]
          });

        }
      });


      if (prevState.chart !== null) {
        option.series[0].data = cache.tempQueue;
        option.series[1].data = cache.locationQueue;

        const arr = cache.locationQueue.map(v => v.value[1]);

        const max = Math.max.apply(null, arr);
        const min = Math.min.apply(null, arr);

        option.series[1].markArea = { //标记区域
          itemStyle: { //全局的
            normal: {color: '#F0F2F5'}
          },
          data: [
            [{
              yAxis: min,//y轴坐标控制
              itemStyle: {
                color: '#F0F2F5'
              }
            }, {
              yAxis: max
            }]
          ]
        };
        prevState.chart.setOption(option, true);
      }

      result.currentInfo = currentInfo
      result.cache = cache
    }

    if (ruleResult && ruleResult !== prevState.ruleResult) {
      if (prevState.chart) {

        option.series[0].markLine.data[0].yAxis = ruleResult.tempTo
        option.series[0].markLine.data[1].yAxis = ruleResult.tempFrom

        option.series[1].markLine.data[0].yAxis = ruleResult.locationTo
        option.series[1].markLine.data[1].yAxis = ruleResult.locationFrom
        prevState.chart.setOption(option, true);
      }
    }


    // 否则，对于state不进行任何操作
    return {...result};
  }


  render() {
    const {
      chartId,
      width = 100,
      height = 300
    } = this.props;

    return (
      <div id={chartId} style={{width: `${width}%`, height}}/>
    )
  }
}

export default CurrentStatusInfo;
